#import "ZJVideoPlayerManager.h"
#import <ZFPlayer/ZFPlayer.h>
#import <ZFPlayer/ZFAVPlayerManager.h>
#import <ZFPlayer/ZFPlayerControlView.h>

@interface ZJVideoPlayerManager()

@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, strong) ZFPlayerControlView *controlView;
@property (nonatomic, strong) ZFAVPlayerManager *playerManager;
@property (nonatomic, assign) NSTimeInterval currentTime;
@property (nonatomic, assign) NSTimeInterval totalTime;
@property (nonatomic, assign) ZJPlayerState currentState;
@property (nonatomic, strong) NSError *lastError;
@property (nonatomic, assign) BOOL isBackTotal;
@end

@implementation ZJVideoPlayerManager

+ (instancetype)shared {
   static ZJVideoPlayerManager *instance = nil;
   static dispatch_once_t onceToken;
   dispatch_once(&onceToken, ^{
       instance = [[ZJVideoPlayerManager alloc] init];
   });
   return instance;
}

- (instancetype)init {
   self = [super init];
   if (self) {
       [self setupPlayer];
   }
   return self;
}

- (void)setupPlayer {
   self.playerManager = [[ZFAVPlayerManager alloc] init];
   self.controlView = [[ZFPlayerControlView alloc] init];
   
   UIView *containerView = [[UIView alloc] init];
   self.player = [ZFPlayerController playerWithPlayerManager:self.playerManager containerView:containerView];
   self.player.controlView = self.controlView;
   
   // 添加播放进度监听
   @weakify(self)
   self.player.playerPlayTimeChanged = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSTimeInterval currentTime, NSTimeInterval duration) {
       @strongify(self)
       self.currentTime = currentTime;
       self.totalTime = duration;
       if ([self.delegate respondsToSelector:@selector(videoPlayer:currentTime:totalTime:)]) {
           [self.delegate videoPlayer:self currentTime:currentTime totalTime:duration];
       }
       if (self.isBackTotal == true && [self.delegate respondsToSelector:@selector(onlyOnceVideoPlayer:totalTime:)]) {
           self.isBackTotal = false;
           [self.delegate onlyOnceVideoPlayer:self totalTime:duration];
       }
   };
   
   // 添加播放状态监听
   self.player.playerDidToEnd = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset) {
       @strongify(self)
       if ([self.delegate respondsToSelector:@selector(videoPlayer:playerStateChanged:)]) {
           [self.delegate videoPlayer:self playerStateChanged:ZFPlayerPlayStatePlaying];
       }
   };
   
   // 添加更多状态监听
   self.player.playerPrepareToPlay = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSURL * _Nonnull assetURL) {
       @strongify(self)
       self.currentState = ZJPlayerStatePlaying;
       if ([self.delegate respondsToSelector:@selector(videoPlayerDidReadyToPlay:)]) {
           [self.delegate videoPlayerDidReadyToPlay:self];
       }
   };
   
   self.player.playerPlayStateChanged = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, ZFPlayerPlaybackState state) {
       @strongify(self)
       switch (state) {
           case ZFPlayerPlayStatePlaying:
               self.currentState = ZJPlayerStatePlaying;
               break;
           case ZFPlayerPlayStatePaused:
               self.currentState = ZJPlayerStatePaused;
               break;
           case ZFPlayerPlayStatePlayFailed:
               self.currentState = ZJPlayerStateError;
               break;
           case ZFPlayerPlayStatePlayStopped:
               self.currentState = ZJPlayerStatePlayEnd; 
               break;
           default:
               self.currentState = ZJPlayerStateUnknown;
               break;
       }
       
       if ([self.delegate respondsToSelector:@selector(videoPlayer:playerStateChanged:)]) {
           [self.delegate videoPlayer:self playerStateChanged:self.currentState];
       }
   };
   
   // 添加缓冲状态监听
   self.player.playerBufferTimeChanged = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSTimeInterval bufferTime) {
       @strongify(self)
       if ([self.delegate respondsToSelector:@selector(videoPlayerBufferingStateChanged:isBuffering:)]) {
           [self.delegate videoPlayerBufferingStateChanged:self isBuffering:bufferTime > 0];
       }
   };
   
   self.player.pauseWhenAppResignActive = YES;
}

- (void)playVideoWithUrl:(NSString *)videoUrl onView:(UIView *)containerView {
    if (!self.player) {
        [self setupPlayer];
    }
    self.isBackTotal = true;
    self.player.containerView = containerView;
    
    // 检查是否是本地视频路径或内网路径
    NSURL *videoURL;
    if ([videoUrl hasPrefix:@"http://"] ||
        [videoUrl hasPrefix:@"https://"] ||
        [videoUrl hasPrefix:@"//"]) {  // 支持相对协议的URL
        if ([videoUrl hasPrefix:@"http://"] || [videoUrl hasPrefix:@"https://"]) {
            videoURL = [NSURL URLWithString:videoUrl];
        } else {
            videoURL = [NSURL fileURLWithPath:videoUrl];
        }
        
        // 检查URL是否有效
        if (!videoURL) {
            NSLog(@"无效的视频URL");
            return;
        }
        
        self.player.assetURL = videoURL;
    }
}

- (void)pause {
   if (self.player) {
       [self.player.currentPlayerManager pause];
   }
}

- (void)resume {
   if (self.player) {
       [self.player.currentPlayerManager play];
   }
}

- (void)stop {
   if (self.player) {
       [self.player.currentPlayerManager stop];
   }
}

- (void)destroyPlayer {
   if (self.player) {
       [self.player.currentPlayerManager stop];
       self.player = nil;
       self.playerManager = nil;
       self.controlView = nil;
   }
}

- (void)seekToTime:(NSTimeInterval)time {
   if (self.player) {
       [self.player seekToTime:time completionHandler:nil];
   }
}

- (float)progress {
   if (self.totalTime == 0) return 0;
   return self.currentTime / self.totalTime;
}

- (void)setMuted:(BOOL)muted {
   if (self.player) {
       self.playerManager.muted = muted;
   }
}

- (void)setPlaybackRate:(float)rate {
   if (self.player) {
       self.playerManager.rate = rate;
   }
}

- (UIImage *)thumbnailImageAtCurrentTime {
   if (self.player) {
       return [self.playerManager thumbnailImageAtCurrentTime];
   }
   return nil;
}

- (void)configurePlayerWithOptions:(NSDictionary *)options {
   if (options[@"volume"]) {
       self.volume = [options[@"volume"] floatValue];
   }
   if (options[@"isLooping"]) {
       self.isLooping = [options[@"isLooping"] boolValue];
   }
   // ... configure other options
}

@end 
